package com.yumeng.common.utils;

import org.springframework.aop.framework.AopContext;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.stereotype.Component;

/**
 * spring工具类 方便在非spring管理环境中获取bean
 *
 * @author wxd
 * @date 2024/5/28 下午2:48
 */
@Component
public class SpringUtils implements BeanFactoryPostProcessor{

    private static ConfigurableListableBeanFactory beanFactory;//bean工厂

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        SpringUtils.beanFactory = beanFactory;
    }

    /**
     * 获取对象
     *
     * @param name
     * @param <T>
     * @return
     */
    public static <T> T getBean(String name){
        return (T) beanFactory.getBean(name);
    }

    /**
     * 获取对象
     *
     * @param clz
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> clz){
        return beanFactory.getBean(clz);
    }

    public static <T> T getBean(String name, Class<T> clz){
        return beanFactory.getBean(name, clz);
    }

    /**
     * 判断bean是否存在
     *
     * @param name
     * @return
     */
    public static boolean containsBean(String name){
        return beanFactory.containsBean(name);
    }

    /**
     * 判断bean是否存在
     *
     * @param type
     * @return
     */
    public static boolean containsBean(Class<?> type){
        String[] names = beanFactory.getBeanNamesForType(type);
        return names.length > 0;
    }


    /**
     * 判断bean是否为Singleton（单例）
     *
     * @param name
     * @return
     */
    public static boolean isSingleton(String name){
        return beanFactory.isSingleton(name);
    }

    /**
     * 获取bean类型
     *
     * @param name
     * @return
     */
    public static Class<?> getType(String name){
        return beanFactory.getType(name);
    }

    /**
     * 获取别名
     *
     * @param name
     * @return
     */
    public static String[] getAliases(String name){
        return beanFactory.getAliases(name);
    }

    /**
     * 获取AOP代理对象
     *
     * @param <T>
     * @return
     */
    public static <T> T getAopProxy(){
        return (T) AopContext.currentProxy();
    }


}
